const router = require("koa-router")();
const JWT = require('jsonwebtoken')
const userList = [
  {
    id: "1",
    username: "admin",
    password: "admin",
    nickname: "简单的程序员",
    avator: "https://robohash.org/5678908765432?set=set4",
    tel: "13111111111",
    sex: "男",
    age: 30,
    sign: "最残酷不过英雄末路",
  },
  {
    id: "2",
    username: "oott",
    password: "oott",
    nickname: "前端程序员",
    avator: "https://robohash.org/7865464?set=set4",
    tel: "13222222222",
    sex: "女",
    age: 20,
    sign: "及时行乐 及时止损",
  },
];
const key = 'werfhniqdklwijkedofnwerkuefbnqodwl;odjfnwiesufkbjdqniwleifjgeirdkefjlnwmoaplefknwisekfjwnqaolwfekjwngiekfjbnwolfdjnweoikfjbwieklwdjkqnowekfjbnwekldfjnqmaowfq'

router.post("/login", (ctx) => {
  // 1. 获取用户和密码
  const { username, password } = ctx.request.body;
  // 2. 查询账户密码
  const item = userList.find(
    (v) => v.username === username && v.password === password
  );
  if (item) {
    const userInfo = {
      id: item.id,
      username: item.username,
      nickname: item.nickname,
      avator: item.avator,
      tel: item.tel,
      sex: item.sex,
      age: item.age,
      sign: item.sign
    }
    // 3. 返回
    ctx.body = {
      code: 200,
      data: {
        // 用户信息
        userInfo,
        // 用户标识 | 令牌
        token: JWT.sign(userInfo, key)
      },
      message: "登录成功",
    };
  } else {
    ctx.body = {
      code: 400,
      message: "账户密码错误,请重新输入~",
    };
  }
});

router.get('/user/info', ctx => {
  const { token } = ctx.request.query;
  try {
    const userInfo = JWT.verify(token, key)
    ctx.body = {
      code: 200,
      data: userInfo,
      message: '用户信息获取成功小'
    }
  } catch {
    ctx.body = {
      code: 400,
      message: '非法token'
    }
  }
  
})
module.exports = router;
